/**
* 全站权限配置
*/

import router from './router'
import store from './store'
import { validatenull } from '@/utils/validate'
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { Message } from 'element-ui'

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  const meta = to.meta || {};

  // 确认用户是否已登录
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      //如果已登录，则重定向到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      //如果用户信息为空则获取用户信息，获取用户信息失败，跳转到登录页
      if(store.getters.roles.length === 0){
        try{
          await store.dispatch('GetUserInfo')
          next({ ...to, replace:true })
        }catch(error){
          await store.dispatch('FedLogOut');
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`);
        }

      }else{

        next();

      }


      
    }
  } else {
    
    //判断是否需要认证，没有登录访问去登录页
    if(meta.isAuth === false){
      next()
    }else{
      next('/login')
    }

  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
